<template>
  <view class="index">
    <view class="top">
      <!-- 左上角信息提示 -->
      <image
        v-if="new_message"
        class="img"
        src="/static/index/message.png"
        mode="scaleToFill"
        @click="message"
      />
      <image
        v-else
        class="img"
        src="/static/index/Frame(4).png"
        mode="scaleToFill"
        @click="message"
      />
      <view class="top-m">
        <image
          class="img"
          src="/static/index/nft_logo1.png"
          mode="scaleToFill"
        />
        <text>{{ t("home.metaverse") }}</text>
      </view>
      <view class="top-r">{{ addrs }}</view>
    </view>
    <!-- 弹窗 -->
    <template>
      <view>
        <teleport to="body">
          <template v-if="displayRecharge">
            <view class="popup-overlay">
              <view class="popup-content">
                <text>invite</text>
                <input
                  type="text"
                  placeholder="Please enter the invitation code"
                  v-model="invite"
                  class="input"
                  placeholder-style="height: 22rpx;
font-size: 20rpx;
font-family: Arial, Arial;
font-weight: 400;
color: rgba(255,255,255,0.5);
line-height: 23rpx;"
                />

                <view class="Ok" @click="Ok">Ok</view>
              </view>
            </view>
          </template>
        </teleport>
      </view>
    </template>
    <!-- //图片滚动 -->
    <scroll class="scroll"></scroll>
    <view class="title">{{ t("home.tishi") }}</view>
    <Scroll class="Scroll"></Scroll>
    <view class="buy">{{ t("home.buyTitle") }}</view>
    <button class="btn" @click="buy">{{ t("home.buyBtn") }}</button>
    <!-- 渲染数据 -->
    <view class="list" v-if="nftList.length">
      <view class="tittle">{{ t("home.listTitle") }}</view>
      <view
        class="item"
        v-for="item in nftList"
        :key="item.id"
        @click="detail(item.id)"
      >
        <view class="line"></view>
        <view class="goods">
          <image class="img" :src="item.goods_pic" mode="scaleToFill" />
          <text class="txt">{{ item.goods_name }}</text>
          <text class="txta">{{ item.goods_price }}USDT</text>
        </view>
      </view>
    </view>
    <view class="home">{{ t("home.helpTitle") }}</view>
    <view class="top1">
      <image class="img" src="/static/index/Frame(5).png" mode="scaleToFill" />
      <view class="Set">{{ t("home.setTitle") }}</view>
      <text>{{ t("home.set") }}</text>
    </view>
    <view class="top1">
      <image class="img" src="/static/index/Frame(6).png" mode="scaleToFill" />
      <view class="Set">{{ t("home.enterTitle") }}</view>
      <text>{{ t("home.enter") }}</text>
    </view>
    <view class="top1">
      <image class="img" src="/static/index/Frame(7).png" mode="scaleToFill" />
      <view class="Set">{{ t("home.addTitle") }}</view>
      <text>{{ t("home.add") }}</text>
    </view>
    <view class="top1">
      <image class="img" src="/static/index/Frame(8).png" mode="scaleToFill" />
      <view class="Set">{{ t("home.saleTitle") }}</view>
      <text>{{ t("home.sale") }}</text>
    </view>
    <view style="position: relative">
      <input
        class="input"
        type="text"
        v-model="msgValue"
        placeholder-style="font-size: 24rpx;
        font-family: Arial, Arial;
        font-weight: 400;
        color: rgba(255,255,255,0.5);"
        :placeholder="t('home.inputValue')"
      />
      <view class="input-r" @click="sedMsg">
        <view class="sending">{{ t("home.input") }}</view>
        <image
          style="width: 40rpx; height: 40rpx"
          src="/static/index/Frame(3).png"
          mode="scaleToFill"
        />
      </view>
    </view>
    <view class="bottom-a">
      <view class="bottom">
        <view class="bot" v-for="(item, index) in imgs" :key="index">
          <image :src="item.src" mode="scaleToFill"></image>
        </view>
      </view>
      <image class="line-a" src="/static/index/Group3.png" mode="scaleToFill" />
      <view class="text-a">Metaverse Subscription</view>
      <view class="text-b">2024NFTMetaverse Subscription</view>
    </view>
    <Notico :show="show" :notice="notice" @cof="() => (show = false)"></Notico>
    <!--  -->
    <div>
      <div
        v-if="isPopupVisible"
        class="modal-overlay"
        @click.self="togglePopup"
      >
        <div class="modal-content">
          {{ t("home.news") }}
          <view class="btnOne">
            <view class="btn1" @click="togglePopup">{{ t("home.off") }}</view>
            <view class="btn1" @click="leaveFor">{{ t("home.before") }}</view>
          </view>
        </div>
      </div>
    </div>
  </view>
</template>

<script setup>
import Notico from "../../components/Notico.vue";
import { useRoute, useRouter } from "vue-router";
import { ref, onMounted, toRaw, nextTick, computed, watch } from "vue";
import { onShow, onHide, onLoad } from "@dcloudio/uni-app";
import { showSuccessToast, closeToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useUserStore } from "../../store/index";
const useStore = useUserStore();
import {
  connectWallet,
  switchNetwork,
  authorizeSignature,
} from "@/networks/web3/bsc.js";
import scroll from "../../components/scroll/index.vue";
import Scroll from "../../components/scroll/scroll.vue";
import api from "../../networks/apis";
//公告弹窗
const show = ref(false);
const route = useRoute();
//公告
const notice = ref("");
const invite = ref("");
const isPopupVisible = ref(false);
const togglePopup = async () => {
  isPopupVisible.value = !isPopupVisible.value;
};
//留言
const msgValue = ref("");
//左上角信息提示
const new_message = ref(false);
//nft列表数组
const nftList = ref([]);
const networkData = ref({
  chainId: "",
  chainName: "",
  rpcUrls: [],
  blockExplorerUrls: [],
  nativeCurrency: {
    symbol: "ETH",
    decimals: 18,
  },
}); //切换网络所需的信息对象
//钱包地址
const address = ref("");
const addrs = ref("");
//获取公告函数
const getnotice = async () => {
  const { data } = await api.notice();
  notice.value = data.notice;
  if (notice.value) {
    show.value = true;
  } else {
    show.value = false;
  }
};
onMounted(async () => {
  invite.value = route.query.inviteCode || "";
  ethereum.on("accountsChanged", (accounts) => {
    //一旦切换账号这里就会执行
    // window.location.reload()
    if (localStorage.getItem("token")) {
      useStore.remove();
      // location.reload()
      uni.switchTab({ url: "/pages/index/index.vue" });
      window.location.reload();
    }
    if (accounts[0] !== useStore.user.address) {
      // location.href = location.origin
      // setTimeout(() =>{
      //   location.href = location.origin
      // }, 1000)
      // location.reload();
    } else if (!accounts[0]) {
      useStore.remove();

      // location.href = location.origin;
      // setTimeout(() => {
      //   location.href = location.origin;
      // }, 1000);
    }
  });

  // notice.value = '公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告公告'
  if (localStorage.getItem("token")) {
    getnotice();
  } else {
    show.value = false;
  }
});
onShow(async () => {
  if (!localStorage.getItem("token")) {
    await authorizeSignature("metaverse")
      .then(() => {})
      .catch(() => {
        showToast("Signature failure");
      });
    address.value = await connectWallet();
    const webLogin = async () => {
      const res = await api.isnewUser(address.value);
      if (res.data.is_new == 1) {
        displayRecharge.value = true;
      } else {
        displayRecharge.value = false;
        login();
      }
    };
    webLogin();
  } else {
    // 信息提示.
    setInterval(async () => {
      const { data } = await api.info();
      if (data.new_message == true) {
        isPopupVisible.value = !isPopupVisible.value;
      }
      new_message.value = data.new_message;
    }, 15000);
  }
  if (useStore.user.address) {
    addrs.value =
      useStore.user?.address.substring(useStore.user.address.length - 7) || "";
  }
  nextTick(async () => {
    chains();
  });
});

const login = async () => {
  const res = await api.login(address.value, invite.value);
  useStore.setToken(res.data.token || "");
  const { data } = await api.userInfo();
  useStore.setuserInfo(data);
  const a = await api.getConfig();
  const b = await api.getNFTlist();
  nftList.value = b.data;
  addrs.value =
    useStore.user?.address.substring(useStore.user.address.length - 7) || "";
  //公告
  getnotice();
};

//获取链的信息
const chains = () => {
  api.chains().then((res) => {
    if (res.code == 0) {
      networkData.value.chainId = res.data.chain_id;
      networkData.value.chainName = res.data.name;
      networkData.value.rpcUrls = res.data.rpc_url;
      networkData.value.blockExplorerUrls = res.data.scan_url;
      // networkData.value.nativeCurrency = res.data.nativeCurrency
      if (window.ethereum.chainId != networkData.value.chainId) {
        setNetwork();
      }
    }
  });
};
//切换网络
const setNetwork = () => {
  switchNetwork(toRaw(networkData.value))
    .then((res) => {
      showToast("Network connection successful");
      console.log("res==", res);
    })
    .catch((err) => {
      showToast("Network connection failure");
      console.log("err==", err);
    });
};

//渲染bottom
const imgs = ref([]);
imgs.value = [
  { id: 1, src: "/static/index/Rectangle25.png" },
  { id: 2, src: "/static/index/Rectangle26.png" },
  { id: 3, src: "/static/index/Rectangle27.png" },
  { id: 4, src: "/static/index/Rectangle28.png" },
  { id: 5, src: "/static/index/Rectangle29.png" },
  { id: 6, src: "/static/index/Rectangle30.png" },
  { id: 7, src: "/static/index/Rectangle31.png" },
  { id: 8, src: "/static/index/Rectangle32.png" },
];
const detail = (id) => {
  uni.navigateTo({
    url: `/pages/bitbeast/index?id=${id}`,
  });
};
//点击购买
const buy = () => {
  uni.navigateTo({
    url: "/pages/NFT/index",
  });
};

//提交留言
const sedMsg = async () => {
  if (msgValue.value) {
    await api.message(msgValue.value);
    msgValue.value = "";
    uni.showToast({
      icon: "none",
      title: t("tost.liuyan"),
    });
  }
};
//跳转消息页
const leaveFor = () => {
  uni.navigateTo({ url: "/pages/leave/index" });
};
//跳转消息页
const message = () => {
  uni.navigateTo({ url: "/pages/leave/index" });
};
//弹窗
const displayRecharge = ref(false);
//点击确定
const Ok = async () => {
  if (!invite.value) {
    uni.showToast({
      icon: "none",
      title: "Please fill in the invitation code",
    });
    return;
  }
  if (!address.value) {
    uni.showToast({
      icon: "none",
      title: "Please sign first",
    });
    return;
  }
  await login();
  displayRecharge.value = false;
};
// watch(displayRecharge, () => {
//   if (!displayRecharge.value) {
//     console.log("abvcg");
//     login();

//   }
// })
</script>

<style scoped lang="scss">
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  text-align: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  width: 200px;
  height: 150rpx;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  .btnOne {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 50rpx;
  }
}
.index {
  width: 750rpx;
  height: 100%;
  padding-top: 60rpx;
  background: #85cec8;
  background: linear-gradient(180deg, #040a40 0%, #042e40 0%, #0d1324 100%);

  .top {
    display: flex;
    align-items: center;
    margin: 0 18rpx 0 36rpx;

    .img {
      width: 40rpx;
      height: 40rpx;
    }

    .top-m {
      width: 168rpx;
      height: 32rpx;
      font-size: 28rpx;
      font-family: Arial, Arial;
      font-weight: bold;
      color: #ffffff;
      display: flex;
      align-items: center;
      margin-left: 210rpx;
      margin-right: 66rpx;

      .img {
        width: 18rpx;
        height: 24rpx;
      }
    }

    .top-r {
      width: 206rpx;
      height: 72rpx;
      font-size: 28rpx;
      font-family: Arial, Arial;
      font-weight: 400;
      color: #ffffff;
      background-image: url("/static/index/Rectangle1.png");
      background-size: cover;
      background-repeat: no-repeat;
      text-align: center;
      line-height: 72rpx;
    }
  }

  .scroll {
    margin-top: 22rpx;
  }

  .title {
    width: 634rpx;
    height: 46rpx;
    font-size: 40rpx;
    font-family: Arial, Arial;
    font-weight: 400;
    color: #ffffff;
    margin: 18rpx auto;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .buy {
    width: 686rpx;
    height: 300rpx;
    font-size: 72rpx;
    font-family: Arial, Arial;
    font-weight: bold;
    color: #ffffff;
    line-height: 84rpx;
    margin: 40rpx auto;
  }

  .btn {
    width: 690rpx;
    height: 120rpx;
    background-image: url("/static/index/Rectangle62.png");
    background-size: cover;
    background-repeat: no-repeat;
    font-size: 48rpx;
    font-family: Arial, Arial;
    font-weight: bold;
    color: #ffffff;
    line-height: 120rpx;
  }

  .list {
    width: 690rpx;
    // height: 940rpx;
    background-image: url("/static/index/Group14.png");
    background-size: cover;
    background-repeat: no-repeat;
    margin: 35rpx auto 0;
    padding-bottom: 44rpx;

    .tittle {
      padding: 36rpx 0 32rpx 0;

      height: 32rpx;
      font-size: 28rpx;
      font-family: Arial, Arial;
      font-weight: bold;
      color: #ffffff;
      line-height: 33rpx;
      margin: 44rpx;
    }

    .line {
      width: 632rpx;
      height: 1rpx;
      box-shadow: 0rpx -2rpx 0rpx 0rpx #000000;
      opacity: 1;
      border: 0rpx solid rgba(107, 107, 107, 0.5);
      margin: 30rpx auto;
    }

    .goods {
      display: flex;
      align-items: center;
      justify-content: space-around;

      .img {
        width: 104rpx;
        height: 104rpx;
      }

      .txt {
        width: 200rpx;
        height: 32rpx;
        font-size: 28rpx;
        font-family: Arial, Arial;
        font-weight: bold;
        color: #dbdbdb;
        line-height: 33rpx;
      }

      .txta {
        width: 200rpx;
        height: 40rpx;
        font-size: 28rpx;
        font-family: Arial, Arial;
        font-weight: 900;
        color: #ffffff;
        line-height: 33rpx;
        margin-left: 60rpx;
        display: flex;
        justify-content: end;
      }
    }
  }

  .home {
    width: 408rpx;
    height: 62rpx;
    font-size: 44rpx;
    font-family: Arial, Arial;
    font-weight: 900;
    color: #ffffff;
    line-height: 52rpx;
    margin: 60rpx auto 36rpx;
  }

  .top1 {
    display: flex;
    flex-direction: column;
    margin-left: 32rpx;
    margin-bottom: 52rpx;

    .img {
      width: 80rpx;
      height: 80rpx;
    }

    .Set {
      width: 370rpx;
      height: 40rpx;
      font-size: 28rpx;
      font-family: Arial, Arial;
      font-weight: 900;
      color: #ffffff;
      line-height: 33rpx;
      margin: 24rpx 10rpx;
    }

    text {
      width: 588rpx;
      height: 78rpx;
      font-size: 22rpx;
      font-family: Arial, Arial;
      font-weight: normal;
      color: rgba(255, 255, 255, 0.5);
      line-height: 26rpx;
    }
  }

  .input {
    height: 94rpx;
    width: 692rpx;
    background-image: url("/static/index/Rectangle68.png");
    background-size: contain;
    background-repeat: no-repeat;
    margin: 0 auto;
    background-size: cover;
    background-repeat: no-repeat;
    color: #fff;
    padding-left: 35rpx;
  }

  .input-r {
    width: 155rpx;
    display: flex;
    align-items: center;
    position: absolute;
    right: 55rpx;
    top: 32rpx;
  }

  .sending {
    width: 108rpx;
    height: 34rpx;
    font-size: 24rpx;
    font-family: Arial, Arial;
    font-weight: 900;
    color: #ffffff;
    line-height: 28rpx;
  }

  .bottom-a {
    width: 100%;
    height: 940rpx;
    background: #0a0e17;

    .bottom {
      padding-top: 30rpx;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 10rpx;
      /* 设置盒子之间的间隔 */
      margin: 100rpx auto 0;

      .bot {
        width: calc(50% - 10rpx);
        /* 一行显示2个盒子，减去盒子之间的间隔 */
        box-sizing: border-box;
        margin-bottom: 6rpx;

        image {
          width: 340rpx;
          height: 116rpx;
        }
      }
    }

    .line-a {
      display: block;
      width: 470rpx;
      height: 0rpx;
      opacity: 1;
      border: 2rpx solid rgba(255, 255, 255, 0.15);
      margin: 80rpx auto 0;
    }

    .text-a {
      text-align: center;
      height: 68rpx;
      font-size: 48rpx;
      font-family: Arial, Arial;
      font-weight: 900;
      color: #ffffff;
      line-height: 56rpx;
      letter-spacing: 1px;
      margin: 60rpx auto 0;
    }

    .text-b {
      text-align: center;
      height: 28rpx;
      font-size: 24rpx;
      font-family: Arial, Arial;
      font-weight: normal;
      color: #ffffff;
      line-height: 28rpx;
      margin: 30rpx auto;
    }
  }
}

.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  width: 688rpx;
  height: 380rpx;
  background-image: url("/static/recharge/Rectangle 36.png");
  background-size: cover;
  background-repeat: no-repeat;
  text-align: center;

  text {
    width: 350rpx;
    height: 36rpx;
    font-size: 32rpx;
    font-family: Arial, Arial;
    font-weight: bold;
    color: #00d084;
    line-height: 38rpx;
    display: block;
    margin: 30rpx auto;
  }

  .input {
    width: 628rpx;
    height: 94rpx;
    background-image: url("/static/recharge/Rectangle 75.png");
    background-size: cover;
    background-repeat: no-repeat;
    margin: 0 auto;
    color: #fff;
  }

  .Ok {
    width: 534rpx;
    height: 92rpx;
    line-height: 92rpx;
    text-align: center;
    background-image: url("/static/Rectangle 62.png");
    background-size: cover;
    background-repeat: no-repeat;
    margin: 50rpx auto;
  }
}
</style>
